/*
 * Copyright 2016-2017 lei.xu<xulei2008xulei@163.com>.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.san21go.jfinfunc.financ.norm;

import org.san21go.jfinfunc.AbstractFunction;
import org.san21go.jfinfunc.FinFuncRuntimeException;
import org.san21go.jfinfunc.jfinfunc.math.AVERAGE;
import org.san21go.jfinfunc.math.stdev.STDEVS;
import org.san21go.jfinfunc.util.DateUtil;

/**
 * SharpeRatio 夏普比率<br/>
 * 表示每承受一单位总风险，会产生多少的超额报酬，可以同时对策略的收益与风险进行综合考虑。<br/>
 * Sharpe Ratio=(Rp−Rf)/σp <br>
 * Rp=策略年化收益率 <br>
 * Rf=无风险利率（默认0.03）<br>
 * σp=策略年化波动率
 * 
 * @author xulei
 *
 */
public class Sharpe extends AbstractFunction<Double> {

	/**
	 * 年化收益率
	 */
	private double[] yieldRates;
	/**
	 * 日期
	 */
	private String[] dates;
	/**
	 * 无风险收益率
	 */
	private double[] freeRiskRates;

	public Sharpe(double[] yieldRates, String[] dates, double[] freeRiskRates) {
		super();
		this.yieldRates = yieldRates;
		this.dates = dates;
		this.freeRiskRates = freeRiskRates;
	}

	@Override
	public Double evaluate() {
		if (yieldRates == null || dates == null || freeRiskRates == null || yieldRates.length == 0
				|| freeRiskRates.length == 0) {
			throw new FinFuncRuntimeException("参数错误");
		}
		if (yieldRates.length != dates.length) {
			throw new FinFuncRuntimeException("参数错误");
		}

		double Rf = new AVERAGE(freeRiskRates).evaluate();
		double Rp = new AVERAGE(yieldRates).evaluate();
		double stdevs = new STDEVS(yieldRates).evaluate();

		String maxDate = Integer.MIN_VALUE + "";
		String minDate = Integer.MAX_VALUE + "";
		for (String date : dates) {
			if (Integer.parseInt(date) > Integer.parseInt(maxDate)) {
				maxDate = date;
			}
			if (Integer.parseInt(date) < Integer.parseInt(minDate)) {
				minDate = date;
			}
		}
		// 求解时间跨度
		double days = DateUtil.diffDate(maxDate, minDate);

		double σp = stdevs * days / 356;

		if (Double.compare(σp, 0) == 0) {
			return 0D;
		}
		double sharpeRatio = (Rp - Rf) / σp;

		return sharpeRatio;
	}

}
